package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBrand;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMtcd;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBrandMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMtcdMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtcdParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMtcdResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyMtcdService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-10-29
 */
@Service
public class BtyMtcdServiceImpl extends ServiceImpl<BtyMtcdMapper, BtyMtcd> implements BtyMtcdService {
    @Resource
    private BtyBrandMapper brandMapper;
    @Override
    public void add(BtyMtcdParam param){
        BtyMtcd entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyMtcdParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyMtcdParam param){
        BtyMtcd oldEntity = getOldEntity(param);
        BtyMtcd newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyMtcdResult findBySpec(BtyMtcdParam param){
        return null;
    }

    @Override
    public List<BtyMtcdResult> findListBySpec(BtyMtcdParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyMtcdParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 导入excel
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchImport(String fileName, MultipartFile file, BtyMtcdParam param){
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            //导入之前删掉之前的数据
            baseMapper.delete(new QueryWrapper<>());
            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    Cell cell0 = row.getCell(1);
                    if (ToolUtil.isNotEmpty(cell0)) {
                        cell0.setCellType(CellType.STRING);
                    }
                    Cell cell = row.getCell(3);
                    if (ToolUtil.isNotEmpty(cell)) {
                        cell.setCellType(CellType.STRING);
                    }
                    Cell cell6 = row.getCell(4);
                    if (ToolUtil.isNotEmpty(cell6)) {
                        cell6.setCellType(CellType.STRING);
                    }
                    //地区
                    String region=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    //用友大区编号
                    String code=row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //店名
                    String dm = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //管理费
                    String glf = row.getCell(3) == null ? "0" : row.getCell(3).getStringCellValue();
                    //抽点费
                    String cdf = row.getCell(4) == null ? "0" : row.getCell(4).getStringCellValue();
                    //用友大区编号
                    if(ToolUtil.isNotEmpty(dm)){
                    BtyMtcd mt=new BtyMtcd();
                    //mt.setId(UUIDUtils.getId());
                    mt.setRegion(region);
                    mt.setCode(code);
                    mt.setDm(dm);
                    mt.setGlf(new BigDecimal(glf).setScale(2, BigDecimal.ROUND_HALF_UP));
                    mt.setCdf(new BigDecimal(cdf).setScale(2, BigDecimal.ROUND_HALF_UP));
                    baseMapper.insert(mt);
                    }
                }
            }
            //导入成功之后按大区生成凭证
            String zdrq=param.getZdrq();

            List<BtyMtcd>list=baseMapper.selectList(new QueryWrapper<BtyMtcd>().gt("glf",0).or().gt("cdf",0).orderByAsc("code"));
            for (BtyMtcd mt : list) {
                //根据店名获取妖码
                String dm = mt.getDm();
                BtyBrand brand = brandMapper.selectOne(new QueryWrapper<BtyBrand>().eq("dm", dm));
                String yaoma = "";
                if (ToolUtil.isNotEmpty(brand)) {
                    yaoma = brand.getYaoma();
                }
                //用友大区编号
                String code = mt.getCode();
                //管理费
                BigDecimal glf = mt.getGlf();
                //抽点费
                BigDecimal cdf = mt.getCdf();
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");
                if (glf.compareTo(BigDecimal.ZERO) == 1) {
                //计提管理费凭证
                sb.append("                {\n" +
                        "                    \"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"\",\n" +
                        "                    \"debitamount\":\"" + glf + "\",\n" +
                        "                    \"explanation\":\"计提管理费\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"660125\",\n" +
                        "                    \"pk_currtype\":\"CNY\"\n" +
                        "                }," +
                        "{\n" +
                        "\t\t\t\t\"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"" + glf + "\",\n" +
                        "                    \"creditquantity\":\"\",\n" +
                        "                    \"debitamount\":\"\",\n" +
                        "                    \"debitquantity\":\"\",\n" +
                        "                    \"detailindex\":\"\",\n" +
                        "                    \"excrate1\":\"\",\n" +
                        "                    \"explanation\":\"计提管理费\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"224102\",\n" +
                        "                    \"pk_currtype\":\"CNY\",\n" +
                        "                    \"price\":\"\"\n" +
                        "                },\n");
            }
                //美团抽点凭证
                if (cdf.compareTo(BigDecimal.ZERO) == 1) {
                    sb.append("                {\n" +
                            "                    \"ass\":[\n" +
                            "                        {\n" +
                            "                            \"checktypecode\":\"2\",\n" +
                            "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                            "                        }\n" +
                            "                    ],\n" +
                            "                    \"creditamount\":\"\",\n" +
                            "                    \"debitamount\":\"" + cdf + "\",\n" +
                            "                    \"explanation\":\"计提美团抽点\",\n" +
                            "                    \"localcreditamount\":\"\",\n" +
                            "                    \"localdebitamount\":\"\",\n" +
                            "                    \"pk_accsubj\":\"660127\",\n" +
                            "                    \"pk_currtype\":\"CNY\"\n" +
                            "                }," +
                            "{\n" +
                            "\t\t\t\t\"ass\":[\n" +
                            "                        {\n" +
                            "                            \"checktypecode\":\"2\",\n" +
                            "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                            "                        }\n" +
                            "                    ],\n" +
                            "                    \"creditamount\":\"" + cdf + "\",\n" +
                            "                    \"creditquantity\":\"\",\n" +
                            "                    \"debitamount\":\"\",\n" +
                            "                    \"debitquantity\":\"\",\n" +
                            "                    \"detailindex\":\"\",\n" +
                            "                    \"excrate1\":\"\",\n" +
                            "                    \"explanation\":\"计提美团抽点\",\n" +
                            "                    \"localcreditamount\":\"\",\n" +
                            "                    \"localdebitamount\":\"\",\n" +
                            "                    \"pk_accsubj\":\"224103\",\n" +
                            "                    \"pk_currtype\":\"CNY\",\n" +
                            "                    \"price\":\"\"\n" +
                            "                },\n");
                }
                sb.append("            ],\n" +
                        "            \"pk_corp\":"+code+",\n" +
                        "            \"pk_glorgbook\":\""+code+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");
                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();
                if(status.equals("falied")){
                    String errormsg = jo.get("errormsg").getAsString();
                    BtyMtcd mtcd=baseMapper.selectOne(new QueryWrapper<BtyMtcd>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(mtcd)){
                        mtcd.setErrormsg(errormsg);
                        baseMapper.updateById(mtcd);
                    }
                   // System.out.println("errormsg:"+errormsg);
                }else{
                    BtyMtcd mtcd=baseMapper.selectOne(new QueryWrapper<BtyMtcd>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(mtcd)){
                        mtcd.setFlag(1);
                        baseMapper.updateById(mtcd);
                    }
                    //System.out.println("凭证生成成功！");
                }
            }

        } catch (Exception e) {
            notNull=false;
            e.printStackTrace();
        }
        return notNull;
    }

    private Serializable getKey(BtyMtcdParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyMtcd getOldEntity(BtyMtcdParam param) {
        return this.getById(getKey(param));
    }

    private BtyMtcd getEntity(BtyMtcdParam param) {
        BtyMtcd entity = new BtyMtcd();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
